//封装购物车模块
import {useUserStore} from './user'
import {defineStore} from 'pinia'
import { computed, ref } from 'vue'
import {inserCartAPI,findNewCartAPI,delCartAPI} from '@/apis/cart'
export const useCartStore = defineStore('cart',() =>{

    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    //1. 定义state - cartList
    const cartList = ref([])

    //获取最新购物车列表action
    const updateNewList = async () =>{
        const res = await findNewCartAPI()
        cartList.value = res.result
    }
    //2. 定义action -addCart
    const addCart = async (goods) =>{
        const {skuId,count} = goods
        if (isLogin.value){
        //登录之后的逻辑
        await inserCartAPI({skuId,count})
        updateNewList()
        }else{
            //添加购物车操作
            //已添加过  -count + 1
            //没有添加过  -直接push
            //通过匹配传递过来的商品对象中的skuId能不能在我们的cartLIst。找到了说明添加过
            const item = cartList.value.find((item) => goods.skuId === item.skuId)
            if(item){
                item.count++
            }else{
                cartList.value.push(goods)
            }
        }


    
    }

    //删除购物车
    const delCart = async (skuId) =>{
        if (isLogin.value){
            //调用接口实现接口购物车删除功能
           await delCartAPI([skuId])
           updateNewList()
        }else{
            const idx = cartList.value.findIndex((item)=> skuId === item.skuId)
            cartList.value.splice(idx,1)
        }

        const idx = cartList.value.findIndex((item)=> skuId === item.skuId)
        cartList.value.splice(idx,1)
    }

    //清除购物车
    const clearCart = () =>{
        cartList.value = []
    }


    //单选功能
    const singleChese = (skuId,selected) =>{
    //通过skuId找到修改的那一项，从而修改selected
    const item = cartList.value.find((item) =>item.skuId === skuId )
    item.selected = selected
    }

    //全选功能
    const allCheck = (selected) => {
        //把cartList中每一项的selected设置为当前全选框的状态
        cartList.value.forEach(item => item.selected = selected)
    }

    //计算属性
    //1.总的数量 count之和
    const allCount = computed(()=> cartList.value.reduce((a,c) => a+c.count,0))
    //2.总价 count*price之和
    const allPrice = computed(()=> cartList.value.reduce((a,c) => a+c.count*c.price,0))
    //3.已选择数量
    const slecentCount = computed(() => cartList.value.filter(item => item.selected).reduce((a,c) => a+c.count,0))
    //4.已选择商品价格合计
    const slecentPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a,c) => a+c.count*c.price,0))
    //是否全选
    const isAll = computed(()=> cartList.value.every((item) => item.selected))
    return {
        cartList,
        addCart,
        delCart,
        allCount,
        allPrice,
        singleChese,
        isAll,
        allCheck,
        slecentPrice,
        slecentCount,
        clearCart,
        updateNewList
    }
},{
    persist:true,
})